package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.paas.field.SaasParticularAttributePoJo;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.InventoryDao;
import com.xbongbong.saas.domain.entity.InventoryProductEntity;
import com.xbongbong.saas.domain.entity.ProductBaseInfoEntity;
import com.xbongbong.saas.domain.entity.ext.InventoryEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.enums.RelativeProductEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.UpdateDataTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.InventoryEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.product.InventoryProductEnum;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.InventoryModel;
import com.xbongbong.saas.model.InventoryProductModel;
import com.xbongbong.saas.model.InventorySubDataModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductBaseInfoModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;

/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/2/15 14:03
 * @since v1.0
 */
@Service("inventoryModel")
public class InventoryModelImpl implements InventoryModel {

    @Resource
    private InventoryDao inventoryDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private InventorySubDataModel inventorySubDataModel;
    @Resource
    private ExplainHelp explainHelp;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private ProductModel productModel;
    @Resource
    private InventoryProductModel inventoryProductModel;
    @Resource
    private ProductBaseInfoModel productBaseInfoModel;

    /**
     * 盘点单数据单条查询
     *
     * @param key    主键ID
     * @param corpid 公司ID
     * @return Integer
     * @author feng.zheng
     * @date 2019/2/15 20:27
     * @since v1.0
     */
    @Override
    public InventoryEntityExt getByKey(Long key, String corpid) {
        InventoryEntityExt entityExt = inventoryDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(entityExt), IndexTypeEnum.IDX_SAAS_INVENTORY_SUB);
        return entityExt;
    }

    /**
     * 保存
     *
     * @param inventoryEntity 盘点单实体
     * @return Integer
     * @author Jian.Wang
     * @date 2019/1/23 20:27
     * @since v1.0
     */
    @Override
    public Integer save(InventoryEntityExt inventoryEntity) throws XbbException {
        if (inventoryEntity.getId() == null || inventoryEntity.getId() == 0L) {
            return insert(inventoryEntity);
        } else {
            return update(inventoryEntity);
        }
    }

    /**
     * 插入
     *
     * @param entity 实体
     * @return 是否成功
     * @throws XbbException 数据库操作异常
     */
    @Override
    public Integer insert(InventoryEntityExt entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_INVENTORY_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = inventoryDao.insert(entity);

        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_INVENTORY);
        paasEsModel.insert(insertDTO);
        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_INVENTORY_SUB);
        return success;

    }

    /**
     * 更新
     *
     * @param entity 实体
     * @return 是否成功
     * @throws XbbException 数据库操作异常
     */
    @Override
    public Integer update(InventoryEntityExt entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_INVENTORY_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = inventoryDao.update(entity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_INVENTORY_SUB);
        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            // 更新时间
            success = inventoryDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            // 更新es
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            paasFormDataEntity.setCreatorId(null);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_INVENTORY);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);

        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        return success;
    }

    /**
     * 获取符合查询条件的记录
     *
     * @param param 查询条件
     * @return 符合查询条件的记录
     */
    @Override
    public List findEntitys(Map<String, Object> param) {
        List<InventoryEntityExt> entitys = inventoryDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_INVENTORY_SUB);
        }
        return entitys;
    }

    /**
     * 获取符合查询条件的记录总数
     *
     * @param param 查询条件
     * @return 符合查询条件的记录总数
     */
    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return inventoryDao.getEntitysCount(param);
    }

    @Override
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_INVENTORY);
        paasEsModel.delete(deleteDTO);

        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_INVENTORY_SUB);
        return inventoryDao.deleteByKey(key,corpid);
    }

    @Override
    public Integer deleteBatch(List<Long> list, String corpid, Integer del) throws XbbException{
        Integer integer = inventoryDao.deleteBatch(list, corpid);
        //ES根据id批量设置del=1
        paasEsModel.deleteBatch(list, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_INVENTORY);

        paasFormSubDataModel.deleteBatchByDataId(list, corpid, IndexTypeEnum.IDX_SAAS_INVENTORY_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> list, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = inventoryDao.updateBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_INVENTORY);
        }
        if (!subList.isEmpty()) {
            inventorySubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> list, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = inventoryDao.updateBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_INVENTORY, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            inventorySubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, boolean needThrow) throws XbbException {
        StandardizeDataUtil.standardizeList(updateList);
        Integer integer = inventoryDao.updateBatch(updateList, corpid);
        paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_INVENTORY, needThrow);
        return integer;
    }

    @Override
    public Integer batchUpdateOwner(List<Long> dataIdList, String corpid, String userId, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer integer = inventoryDao.batchUpdateOwner(dataIdList, corpid, userId);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (Long id : dataIdList){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(corpid+"_"+id);
            Map<String, Object> map = new HashMap<>();
            map.put(FieldTypeEnum.OWNERID.getAlias(), userId);
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_INVENTORY);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList, refreshPolicy);
        return integer;
    }

    @Override
    public List<String> getCorpids() {
        return inventoryDao.getCorpids();
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return inventoryDao.findEntitys(param);
    }

    /**
     * 编辑时格式化解释
     *
     * @param formatExplainDTO 入参
     * @throws XbbException 异常
     * @author feng.zheng
     * @date 2019/2/27 20:11
     */
    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        String corpid = formatExplainDTO.getCorpid();
        String platForm = formatExplainDTO.getPlatform();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            Integer fieldType = fieldAttrEntity.getFieldType();
            if (Objects.equals(fieldType, FieldTypeEnum.SELECT_PRODUCT.getType())) {
                fieldAttrEntity.setSupportScanning(BasicConstant.ONE);
                //已经有出入库的盘点单编辑的时候不允许编辑产品
                boolean isEditable = true;
                JSONObject data = formatExplainDTO.getResult();
                Long instockId = data.getLong(InventoryEnum.INSTOCK_ID.getAttr());
                Long outstockId = data.getLong(InventoryEnum.OUTSTOCK_ID.getAttr());
                if ((Objects.nonNull(instockId) && instockId > 0) || (Objects.nonNull(outstockId) && outstockId > 0) || (Objects.nonNull(formatExplainDTO.getHasSheetInApproval()) && formatExplainDTO.getHasSheetInApproval())) {
                    isEditable = false;
                }
                explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.INVENTORY, corpid, BasicConstant.ONE, false);
                if (!isEditable && (Objects.isNull(formatExplainDTO.getFromCopy()) || !formatExplainDTO.getFromCopy())) {
                    fieldAttrEntity.setEditable(0);
                    //fieldAttrEntity.setNoEditable(1);
                    List<? extends FieldAttrEntity> subExplainList = fieldAttrEntity.getSubForm().getItems();
                    subExplainList.forEach(item -> item.setEditable(0));
                    fieldAttrEntity.getSubForm().setItems(subExplainList);
                }
                if (Objects.equals(platForm, PlatFormEnum.DINGTALK.getValue())) {
                    SaasParticularAttributePoJo saasParticularAttributePoJo = fieldAttrEntity.getSaasParticularAttributePoJo();
                    saasParticularAttributePoJo.setProductRelyAttr(InventoryEnum.WAREHOUSE_ID.getAttr());
                }
            } else if (Objects.equals(fieldAttrEntity.getAttr(),InventoryEnum.INVENTORY_TYPE.getAttr())){
                fieldAttrEntity.setEditable(0);
            } else if (Objects.equals(fieldAttrEntity.getAttr(),InventoryEnum.WAREHOUSE_ID.getAttr())){
                if (Objects.nonNull(formatExplainDTO.getHasSheetInApproval()) && formatExplainDTO.getHasSheetInApproval()) {
                    fieldAttrEntity.setEditable(0);
                }
            }
        }
    }

    /**
     * 编辑时将获取数据格式化
     *
     * @param formDataUpdateGetDTO saas编辑数据
     * @param result               要返回的jsonobject
     * @throws XbbException 业务异常
     * @author feng.zheng
     * @date 2019/1/22 15:28
     */
    @Override
    public void formatData(SaasAnalysisDataDTO formDataUpdateGetDTO, JSONObject result) throws XbbException {
//        formatProduct4Show(result, formDataUpdateGetDTO);
        showFormatHelp.formatLinkBusiness4Show(result, InventoryEnum.WAREHOUSE_ID.getAttr(), InventoryEnum.WAREHOUSE_ID_LINKED_TEXT.getAttr(), InventoryEnum.WAREHOUSE_ID.getFieldType());
    }

    /**
     * 获取inventoryProducts和productBaseInfoList
     *
     * @param corpid
     * @param inventoryProducts
     * @param productBaseInfoList
     * @param data
     * @param productMap
     * @throws XbbException
     */
    private void formatProductList(String corpid, List<InventoryProductEntity> inventoryProducts, List<ProductBaseInfoEntity> productBaseInfoList, JSONObject data, Map<Long, ProductEntityExt> productMap) throws XbbException {
        Integer sort = 0;
        JSONArray productArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, InventoryEnum.PRODUCT.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject productArrayJSONObject = productArray.getJSONObject(i);
            sort++;
            // 页面传入的产品id
            Long pageProductId = FastJsonHelper.getLongOrDefaultFromFormData(productArrayJSONObject, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            // 产品数量
            Double productNum = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.NUM.getSaasAttr(), 0D);
            // 账面数量
            Double oriNum = getDoubleOrDefaultFromFormData(productArrayJSONObject, StringConstant.ORI_NUM, 0D);
            // 仓库
            JSONObject warehouse = FastJsonHelper.getJsonObjectFromFormData(productArrayJSONObject, RelativeProductEnum.WAREHOUSE.getSaasAttr());
            Long warehouseId = 0L;
            if (warehouse != null && warehouse.size() > 0) {
                warehouseId = warehouse.getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
            }
            // 批次
            String batch = FastJsonHelper.getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.BATCH.getSaasAttr(), "");
            // 生产日期
            Long date = DateTimeUtil.getInt(FastJsonHelper.getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.PRODUCE_DATE.getSaasAttr(), ""), DateUtil.SDFDate);
            // 保质期 存的是天数
            Long guaranteePeriod = FastJsonHelper.getLongFromFormData(productArrayJSONObject, RelativeProductEnum.GUARANTEE_PERIOD.getSaasAttr());
            // 产品备注
            String memo = FastJsonHelper.getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.MEMO.getSaasAttr(), "");
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String specification = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String productName = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                Double price = getDoubleOrDefaultFromFormData(productObject, ProductEnum.PRICE.getAttr(), 0D);
                String productNo = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                String unit = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                String barcode = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.BARCODE.getAttr(), "");
                Long parentId = FastJsonHelper.getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                InventoryProductEntity productEntity = new InventoryProductEntity();
                productEntity.setBarcode(barcode);
                productEntity.setCorpid(corpid);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setOriNum(oriNum);
                productEntity.setProductPrice(price);
                productEntity.setProductNum(productNum);
                productEntity.setProductName(productName);
                productEntity.setProductNo(productNo);
                productEntity.setWarehouseId(warehouseId);
                productEntity.setProductSpecification(specification);
                productEntity.setProductUnit(unit);
                productEntity.setSort(sort);
                // 增加关联id 为了和baseInfo有关联
                Long id = new Random().nextLong();
                productEntity.setId(id);
                inventoryProducts.add(productEntity);
                // baseInfo冗余信息
                ProductBaseInfoEntity productBaseInfoEntity = new ProductBaseInfoEntity();
                productBaseInfoEntity.setBatch(batch);
                if (guaranteePeriod != null) {
                    productBaseInfoEntity.setGuaranteePeriod(guaranteePeriod * 86400);
                }
                productBaseInfoEntity.setProduceDate(date);
                productBaseInfoEntity.setRefId(id);
                productBaseInfoEntity.setRefType(XbbRefTypeEnum.INVENTORY_PRODUCT.getCode());
                productBaseInfoEntity.setMemo(memo);
                productBaseInfoList.add(productBaseInfoEntity);
            }
        }
    }

    private void formatNewProductList(String corpid, List<InventoryProductEntity> inventoryProducts, List<ProductBaseInfoEntity> productBaseInfoList, JSONArray productArray, Map<Long, ProductEntityExt> productMap) throws XbbException {
        Integer sort = 0;
        for (int i = 0; i < productArray.size(); i++) {
            sort++;
            JSONObject pageProductObject = productArray.getJSONObject(i);
            Long pageProductId = pageProductObject.getLong(InventoryProductEnum.PRODUCT.getAttr());
            Double oriNum = getDoubleOrDefaultFromFormData(pageProductObject, InventoryProductEnum.STOCK.getAttr(), 0D);
            Double productNum = getDoubleOrDefaultFromFormData(pageProductObject, InventoryProductEnum.NUM.getAttr(), 0D);
            String memo = FastJsonHelper.getStringOrDefaultFromFormData(pageProductObject, InventoryProductEnum.MEMO.getAttr(), "");
            String batch = FastJsonHelper.getStringOrDefaultFromFormData(pageProductObject, InventoryProductEnum.BATCH.getAttr(), "");
            Long date = FastJsonHelper.getLongOrDefaultFromFormData(pageProductObject, InventoryProductEnum.PRODUCE_DATE.getAttr(), 0L);
            Long guaranteePeriod = FastJsonHelper.getLongOrDefaultFromFormData(pageProductObject, InventoryProductEnum.GUARANTEE_PERIOD.getAttr(), 0L);
            Long subProductId = FastJsonHelper.getLongFromFormData(pageProductObject, BusinessConstant.PRODUCT_SUB_ID);
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String specification = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String productName = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                Double price = getDoubleOrDefaultFromFormData(productObject, ProductEnum.PRICE.getAttr(), 0D);
                String productNo = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                String unit = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                String barcode = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.BARCODE.getAttr(), "");
                Long parentId = FastJsonHelper.getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                boolean enableMultiUnit = Objects.equals(productObject.getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()),1);
                InventoryProductEntity productEntity = new InventoryProductEntity();
                productEntity.setBarcode(barcode);
                productEntity.setCorpid(corpid);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setOriNum(oriNum);
                productEntity.setProductPrice(price);
                productEntity.setProductNum(productNum);
                productEntity.setProductName(productName);
                productEntity.setProductNo(productNo);
                productEntity.setProductSpecification(specification);
                productEntity.setProductUnit(unit);
                productEntity.setSort(sort);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(InventoryProductEnum.PRODUCT.getAttr(), pageProductId);
                jsonObject.put(InventoryProductEnum.NUM.getAttr(), productNum);
                jsonObject.put(InventoryProductEnum.STOCK.getAttr(), oriNum);
                jsonObject.put(InventoryProductEnum.MEMO.getAttr(), memo);
                jsonObject.put(InventoryProductEnum.BATCH.getAttr(), batch);
                jsonObject.put(InventoryProductEnum.PRODUCE_DATE.getAttr(), date);
                jsonObject.put(InventoryProductEnum.UNIT.getAttr(), unit);
                if (enableMultiUnit) {
                    productEntity.setProductUnit(pageProductObject.getString(ProductEnum.UNIT.getAttr()));
                    jsonObject.put(InventoryProductEnum.UNIT.getAttr(), pageProductObject.get(ProductEnum.UNIT.getAttr()));
                }
                // 24049 【盘点单】盘点单审批，审批中，产品自定义字段内容没有展示
                for (String attr : pageProductObject.keySet()) {
                    if (!jsonObject.containsKey(attr)) {
                        jsonObject.put(attr, pageProductObject.get(attr));
                    }
                }
                productEntity.setData(jsonObject);
                // 增加关联id 为了和baseInfo有关联
                Long id = Long.valueOf(-sort);
                if (Objects.nonNull(subProductId)) {
                    id = subProductId;
                }
                productEntity.setId(id);
                inventoryProducts.add(productEntity);
                // baseInfo冗余信息

                ProductBaseInfoEntity productBaseInfoEntity = new ProductBaseInfoEntity();
                productBaseInfoEntity.setBatch(batch);
                if (guaranteePeriod != null) {
                    productBaseInfoEntity.setGuaranteePeriod(guaranteePeriod * 86400);
                    jsonObject.put(InventoryProductEnum.GUARANTEE_PERIOD.getAttr(), guaranteePeriod);
                }
                productBaseInfoEntity.setProduceDate(date);
                productBaseInfoEntity.setRefId(id);
                productBaseInfoEntity.setRefType(XbbRefTypeEnum.INVENTORY_PRODUCT.getCode());
                productBaseInfoEntity.setMemo(memo);
                productBaseInfoList.add(productBaseInfoEntity);
            }
        }
    }

    @Override
    public JSONObject formatSingleProduct(InventoryProductEntity inventoryProductEntity,ProductBaseInfoEntity productBaseInfoEntity) {
        JSONObject json = inventoryProductEntity.getData();
        if (Objects.isNull(json) || json.isEmpty()){
            json = new JSONObject();
            for (InventoryProductEnum inventoryProductEnum :InventoryProductEnum.values()){
                String attr = inventoryProductEnum.getAttr();
                switch (inventoryProductEnum){
                    case PRODUCT:
                        json.put(attr,inventoryProductEntity.getProductId());
                        break;
                    case NUM:
                        json.put(attr,inventoryProductEntity.getProductNum());
                        break;
                    case MEMO:
                        json.put(attr,productBaseInfoEntity.getMemo());
                        break;
                    case INVENTORY:
                        json.put(attr,inventoryProductEntity.getProductNum() - inventoryProductEntity.getOriNum());
                        break;
                    case UNIT:
                        json.put(attr,inventoryProductEntity.getProductUnit());
                        break;
                    default:
                        break;
                }
            }
        } else if (Objects.equals(json.getDouble(SelectProductEnum.GUARANTEE_PERIOD.getAttr()), 0D)) {
            if (Objects.equals(json.getLong(SelectProductEnum.PRODUCE_DATE.getAttr()), 0L) || Objects.isNull(json.get(SelectProductEnum.PRODUCE_DATE.getAttr()))) {
                json.remove(SelectProductEnum.GUARANTEE_PERIOD.getAttr());
            }
        }
        return json;
    }

    @Override
    public void formatProduct4Show2(Long dataId, String corpid, JSONObject data, UpdateDataTypeEnum updateDataTypeEnum) throws XbbException {
        List<InventoryProductEntity> inventoryProductEntityList = new ArrayList<>();
        // 盘点单产品冗余信息
        List<ProductBaseInfoEntity> productBaseInfoEntityList = new ArrayList<>();
        Set<Long> productIdList = new HashSet<>();
        // 审批数据获取
        if (Objects.isNull(dataId) || Objects.equals(dataId, 0L)) {
            if (data.get(InventoryEnum.PRODUCT.getAttr()) instanceof JSONObject) {
                JSONArray productArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, InventoryEnum.PRODUCT.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
                Map<Long, ProductEntityExt> productMap = productModel.getProductMap(productIdList, corpid, productArray);
                formatProductList(corpid, inventoryProductEntityList, productBaseInfoEntityList, data, productMap);
            } else {
                JSONArray jsonArray = data.getJSONArray(InventoryEnum.PRODUCT.getAttr());
                if (Objects.nonNull(jsonArray)) {
                    List<Long> productIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        // 页面传入的产品的id
                        Long productId = object.getLong(InventoryProductEnum.PRODUCT.getAttr());
                        if (Objects.nonNull(productId)) {
                            productIdIn.add(productId);
                            productIdList.add(productId);
                        }
                    }
                    // 获取产品信息
                    Map<Long, ProductEntityExt> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    if (productIdIn.size() >= 1) {
                        // 从产品表中获取对应的产品信息
                        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        params.put("corpid", corpid);
                        params.put("idIn", productIdIn);
                        params.put("del", 0);
                        List<ProductEntityExt> productModelEntitys = productModel.findEntitys(params);
                        if (productModelEntitys != null) {
                            for (ProductEntityExt entity : productModelEntitys) {
                                productMap.put(entity.getId(), entity);
                            }
                        }
                    }
                    formatNewProductList(corpid, inventoryProductEntityList, productBaseInfoEntityList, jsonArray, productMap);
                }
            }
        } else {
            // 检索del=0和del=6的数据，del=6是工作流中审批节点拒绝和撤回产生的数据，不是通过审批拒绝、撤回的数据不会产生del=6的数据，如果拒绝和撤回重新提交后，del=6将会被置回del=0

            inventoryProductEntityList = inventoryProductModel.getProductsByInventoryId(dataId, corpid, Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_FAILED.getDel()));

            List<Long> refIdList = new ArrayList<>();
            inventoryProductEntityList.forEach(item -> {
                productIdList.add(item.getProductId());
                refIdList.add(item.getId());
            });
            if (refIdList.isEmpty()){
                return;
            }
            productBaseInfoEntityList =  productBaseInfoModel.getProductBaseInfoList(corpid,XbbRefTypeEnum.INVENTORY_PRODUCT.getCode(),refIdList);
        }
        //查看编辑的时候库存数量(非实际数量)是不可修改的，所以只需要查询盘点单生成时的数量
        JSONArray productArray = new JSONArray();
        for (InventoryProductEntity inventoryProductEntity : inventoryProductEntityList) {
            JSONObject json = inventoryProductEntity.getData();
            //兼容部分老数据
            if (Objects.isNull(json)) {
                Map<Long,ProductBaseInfoEntity> baseInfoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (ProductBaseInfoEntity entity : productBaseInfoEntityList){
                    baseInfoMap.put(entity.getRefId(),entity);
                }
                ProductBaseInfoEntity productBaseInfoEntity = baseInfoMap.getOrDefault(inventoryProductEntity.getId(),new ProductBaseInfoEntity());
                json = formatSingleProduct(inventoryProductEntity,productBaseInfoEntity);
                json.put(InventoryProductEnum.STOCK.getAttr(),inventoryProductEntity.getOriNum());
            }
            if (Objects.equals(json.getDouble(SelectProductEnum.GUARANTEE_PERIOD.getAttr()), 0D)) {
                if (Objects.equals(json.getLong(SelectProductEnum.PRODUCE_DATE.getAttr()), 0L) || Objects.isNull(json.getLong(SelectProductEnum.PRODUCE_DATE.getAttr()))) {
                    json.remove(SelectProductEnum.GUARANTEE_PERIOD.getAttr());
                }
            }
            json.put(BusinessConstant.PRODUCT_SUB_ID,inventoryProductEntity.getId());
            // 工作流生成入库单，需要此属性，所以增加一个
            json.put(BusinessConstant.REF_PRODUCT_ID, json.get(BusinessConstant.PRODUCT_SUB_ID));
            if (Objects.nonNull(json.getString(InventoryProductEnum.BATCH.getAttr()))) {
                JSONObject batchObj = new JSONObject();
                batchObj.put("text",json.getString(InventoryProductEnum.BATCH.getAttr()));
                batchObj.put("value",json.getString(InventoryProductEnum.BATCH.getAttr()));
                json.put(InventoryProductEnum.BATCH.getAttr(),batchObj);
            }
            if (!json.containsKey(RelativeProductEnum.PROFIT_STATUS.getAttr())) {
                String attrValue = "";
                double leftNum = Arith.sub(inventoryProductEntity.getOriNum(), inventoryProductEntity.getProductNum());
                if (leftNum > 0) {
                    attrValue = attrValue + I18nMessageUtil.getMessage(I18nStringConstant.INVENTORY_LOSSES) + "：" + leftNum;
                }
                if (leftNum < 0) {
                    attrValue = attrValue + I18nMessageUtil.getMessage(I18nStringConstant.INVENTORY_SURPLUS) + "：" + Math.abs(leftNum);
                }
                json.put(RelativeProductEnum.PROFIT_STATUS.getAttr(), attrValue);
            }
            productArray.add(json);
        }
        data.put(InventoryEnum.PRODUCT.getAttr(),productArray);
    }
}
